<template>
  <div>
    <el-form ref="form" label-width="80px" :model="spu">
      <el-form-item label="SPU名称">
        <el-input placeholder="SPU名称" v-model="spu.spuName"></el-input>
      </el-form-item>

      <el-form-item label="品牌">
        <el-select
          placeholder="请选择品牌"
          v-model="spu.tmId"
          @change="handleSelect"
        >
          <el-option
            :label="tm.tmName"
            :value="tm.id"
            v-for="tm in tradeMarkList"
            :key="tm.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="SPU描述">
        <el-input
          type="textarea"
          rows="4"
          placeholder="描述"
          v-model="spu.description"
        ></el-input>
      </el-form-item>

      <!-- 
        action:图片上传地址
        list-tyle：文件列表类型
        file-list:显示照片墙
       -->
      <el-form-item label="SPU图片">
        <el-upload
          action="/dev-api/admin/product/fileUpload"
          list-type="picture-card"
          :file-list="spuImageList"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-success="handlerSuccess"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>

      <!--  v-if="unSelectSaleAttr.length != 0" -->
      <el-form-item label="销售属性">
        <el-select
          :placeholder="`还有${unSelectSaleAttr.length}未选择`"
          v-model="attrIdAndAttrName"
        >
          <el-option
            :value="`${unselect.id}:${unselect.name}`"
            :label="unselect.name"
            v-for="(unselect, index) in unSelectSaleAttr"
            :key="unselect.id"
          ></el-option>
        </el-select>
        <el-button
          type="primary"
          icon="el-icon-plus"
          style="margin-left: 20px"
          :disabled="!attrIdAndAttrName"
          @click="addSaleAttr"
          >添加销售属性</el-button
        >
        <el-table style="width: 100%" border :data="spu.spuSaleAttrList">
          <el-table-column
            type="index"
            label="序号"
            width="80px"
            align="center"
          >
          </el-table-column>
          <el-table-column prop="saleAttrName" label="属性名" width="width">
          </el-table-column>
          <el-table-column prop="prop" label="属性值名称列表" width="width">
            <template slot-scope="{ row }">
              <el-tag
                :key="tag.id"
                v-for="(tag, index) in row.spuSaleAttrValueList"
                closable
                :disable-transitions="false"
                @close="row.spuSaleAttrValueList.splice(index, 1)"
              >
                {{ tag.saleAttrValueName }}
              </el-tag>
              <el-input
                class="input-new-tag"
                v-if="row.inputVisible"
                v-model="row.inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm(row)"
                @blur="handleInputConfirm(row)"
              >
              </el-input>
              <el-button
                v-else
                class="button-new-tag"
                size="small"
                @click="addSaleAttrValue(row)"
                >添加</el-button
              >
            </template>
          </el-table-column>
          <el-table-column prop="prop" label="操作" width="width">
            <template slot-scope="{ row, $index }">
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="spu.spuSaleAttrList.splice($index, 1)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="addOrUpdateSpu">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: "SpuForm",
  data() {
    return {
      dialogImageUrl: "",
      dialogVisible: false,
      //因为添加和修改都要用这个对象，修改时这个spu中是有数据的，但是添加时没有发送请求，所以spu为空，我们要给spu内部加上属性
      spu: {
        category3Id: 0,
        description: "",
        id: 0,
        spuImageList: [
          // {
          //   id: 0,
          //   imgName: "string",
          //   imgUrl: "string",
          //   spuId: 0,
          // },
        ],
        spuName: "",
        //品牌id
        tmId: "",
        spuSaleAttrList: [
          // {
          //   baseSaleAttrId: 0,
          //   id: 0,
          //   saleAttrName: "",
          //   spuId: 0,
          //   spuSaleAttrValueList: [
          //     // {
          //     //   baseSaleAttrId: 0,
          //     //   id: 0,
          //     //   isChecked: "string",
          //     //   saleAttrName: "string",
          //     //   saleAttrValueName: "string",
          //     //   spuId: 0,
          //     // },
          //   ],
          // },
        ],
      },
      tradeMarkList: [],
      spuImageList: [],
      saleAttrList: [],

      //收集未选择的销售属性的id,通过计算属性计算出来的
      attrIdAndAttrName: "",
    };
  },

  methods: {
    //照片墙图片上传成功
    handlerSuccess(response, file, fileList) {
      //收集图片的信息
      console.log(response);
      this.spuImageList = fileList;
      console.log(this.spuImageList);
    },

    //照片墙移除事件
    handleRemove(file, fileList) {
      // file是删除的内容，fileList是删除后剩余的数据
      //收集剩余的照片墙内容
      this.spuImageList = fileList;
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },

    //初始化数据,在父组件中调用
    async initSpuData(spu) {
      let spuResult = await this.$API.spu.reqSpu(spu.id);
      if (spuResult.code == 200) {
        this.spu = spuResult.data;
      }
      //所有数据
      let tradeMarkList = await this.$API.spu.reqTradeMarkList();
      if (tradeMarkList.code == 200) {
        this.tradeMarkList = tradeMarkList.data;
      }

      let reqImageList = await this.$API.spu.reqSpuImageList(spu.id);
      if (reqImageList.code == 200) {
        //照片墙上传的图片对象必须要用name 和url两个属性，所以要进行修改服务器返回的数据添加这两个属性
        let listArr = reqImageList.data;
        listArr.forEach((element) => {
          element.name = element.imgName;
          element.url = element.imgUrl;
        });
        this.spuImageList = listArr;
      }

      let BaseSaleAttrList = await this.$API.spu.reqBaseSaleAttrList();
      if (BaseSaleAttrList.code == 200) {
        this.saleAttrList = BaseSaleAttrList.data;
      }
    },

    handleSelect() {},

    //添加销售属性
    addSaleAttr() {
      //把收集到的id和name分割添加到销售属性的数组中
      console.log("收集的数据为", this.attrIdAndAttrName);
      const [baseSaleAttrId, saleAttrName] = this.attrIdAndAttrName.split(":");
      let newSaleAttr = {
        baseSaleAttrId,
        saleAttrName,
        spuSaleAttrValueList: [],
      };
      this.spu.spuSaleAttrList.push(newSaleAttr);

      this.attrIdAndAttrName = "";
    },

    //点击添加销售属性按钮时
    addSaleAttrValue(row) {
      this.$set(row, "inputVisible", true);
      //这是收集的新增的销售属性值
      this.$set(row, "inputValue", "");
      //聚焦
      this.$nextTick(() => {
        this.$refs.saveTagInput.focus();
      });
    },

    //input失去焦点
    handleInputConfirm(row) {
      //收集到的新增的属性值进行展示  baseSaleAttrId, saleAttrValueName,
      const { baseSaleAttrId, inputValue } = row;
      //新增的属性值不能为空
      if (!inputValue.trim()) {
        this.$message({
          type: "warning",
          message: "值不能为空",
        });
        this.$nextTick(() => {
          this.$refs.saveTagInput.focus();
        });
        return;
      }

      //属性值不能重复
      let result = row.spuSaleAttrValueList.some(
        (item) => item.saleAttrValueName == inputValue
      );
      if (result) {
        this.$message({
          message: "值不能重复",
          type: "warning",
        });
        this.$nextTick(() => {
          this.$refs.saveTagInput.focus();
        });
        return;
      }
      let newSaleAttrName = { baseSaleAttrId, saleAttrValueName: inputValue };
      row.spuSaleAttrValueList.push(newSaleAttrName);
      row.inputVisible = false;
    },

    //点击保存按钮整理参数发送请求
    async addOrUpdateSpu() {
      //去掉图片数组中的name和url
      this.spu.spuImageList = this.spuImageList.map((item) => {
        return {
          imgName: item.name,
          imgUrl: item.url || (item.response && item.response.data),
          // 图片不显示的把保存那里图片不显示的把保存那里imgUrl: item.url || (item.response && item.response.data)
        };
      });
      try {
        let result = await this.$API.spu.reqAddOrUpdateSpu(this.spu);
        this.$message({
          message: this.spu.id ? "修改成功" : "添加成功",
          type: "success",
        });
        //父组件显示
        this.$emit("changeScene", {
          scene: 0,
          flag: this.spu.id ? "修改" : "添加",
        });
        Object.assign(this._data, this.$options.data());
      } catch (error) {}
    },

    async addSpuData(category3Id) {
      this.spu.category3Id = category3Id;
      //所有数据
      let tradeMarkList = await this.$API.spu.reqTradeMarkList();
      if (tradeMarkList.code == 200) {
        this.tradeMarkList = tradeMarkList.data;
      }
      let BaseSaleAttrList = await this.$API.spu.reqBaseSaleAttrList();
      if (BaseSaleAttrList.code == 200) {
        this.saleAttrList = BaseSaleAttrList.data;
      }
    },

    cancel() {
      this.$emit("changeScene", { scene: 0, flag: "" });
      Object.assign(this._data, this.$options.data());
    },
  },

  computed: {
    //计算出还未选择的销售属性
    unSelectSaleAttr() {
      return this.saleAttrList.filter((item) => {
        return this.spu.spuSaleAttrList.every((item1) => {
          return item.name != item1.saleAttrName;
        });
      });
    },
  },
};
</script>



<style>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>